from flask import Flask, render_template, flash, redirect, url_for
import os
from datetime import datetime
from config import Config
import shutil

app = Flask(__name__)
app.config.from_object(Config)


def get_files(father_path):
    if os.path.exists(father_path):
        files = os.listdir(r"%s" % father_path)
        abs_path_list = []
        mtimes = []
        for file in files:
            try:
                filepath = os.path.join(os.path.abspath(father_path), file)
                abs_path_list.append(filepath)
                mtimes.append(datetime.fromtimestamp(os.path.getmtime(filepath)).strftime("%Y-%m-%d"))
            except OSError as error:
                print(error)
        return list(zip(abs_path_list, mtimes))
    else:
        print('路径不存在')


def delete_file(filepath):
    if os.path.exists(filepath):
        if os.path.isdir(filepath):
            shutil.rmtree(filepath)
        else:
            os.remove(filepath)
    else:
        return


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/files')
def files():
    f = get_files(app.config['FATHER_PATH'])
    return render_template('files.html', f=f)


@app.route('/delete/<name>')
def delete(name):
    delete_file(name)
    flash('文件：%s删除成功' % name)
    return redirect(url_for('files'))


if __name__ == '__main__':
    app.run()
